import { middleLogger } from '@/utils/back/devlogger';
import { pathsToRegs } from '@/utils/common';
import { NextRequest, NextResponse } from 'next/server';

const originWhitList = [] as string[];

const corsOptions = {
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers':
    'Content-Type, Authorization, Content-Length, X-APP-Secret',
  'Access-Control-Allow-Credentials': 'true',
};

const corsPaths = ['/api/front/', '/api/logout'];

export default function corsMiddleware(req: NextRequest, next: Fn) {
  const corsPathRegs = pathsToRegs(corsPaths);
  if (corsPathRegs.some(reg => reg.test(req.nextUrl.pathname))) {
    middleLogger.info('corsMiddleware', req.nextUrl.pathname, req.method);
    const origin = req.headers.get('host')?.replace(/:\d+$/, '') ?? '';
    const sourceOrigin = new URL(req.headers.get('referer') ?? req.url).origin;

    const isPreflight = req.method === 'OPTIONS';
    if (isPreflight) {
      return new Response(null, {
        status: 204,
        headers: Object.assign(
          { 'Access-Control-Allow-Origin': sourceOrigin },
          // { 'Access-Control-Allow-Origin': 'http://' + 'cc.com' + ':9000' },
          corsOptions
        ),
      });
    }

    const needCheckOrigin = originWhitList.length > 0;
    const isAllowedOrigin =
      !needCheckOrigin ||
      originWhitList.some(re => (sourceOrigin || '').match(re));
    if (!isAllowedOrigin) {
      return new Response('Not allowed', { status: 403 });
    } else {
      const res = NextResponse.next();
      res.headers.set('Access-Control-Allow-Origin', sourceOrigin);
      Object.entries(corsOptions).forEach(([key, value]) => {
        res.headers.set(key, value);
      });

      return res;
    }
  }

  return next(req);
}
